package com.burgeon.backend.Util.wechatUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.web.client.RestTemplate;

public class WeGetAccessToken {


    public static String getAccessToken() {
        String accessToken = null;
        String grantType = "client_credential";
        String appid = "wx64acb710347f7e5c";//wx42580ac72346c4d6,,wxbdff332627c9cf4f;
        //3dbfb9980eb26e16c376d98738a29b04
        String secret = "3dbfb9980eb26e16c376d98738a29b04";//212fabf6be2bdd8c6b3925d2d06cce41;;;5ffc821ad0edf9e013137b1c619b3908
        String url = "https://api.weixin.qq.com/cgi-bin/token?" +
                "grant_type=" + grantType +
                "&appid=" + appid +
                "&secret=" + secret;
//        try {
//            URL urlGet = new URL(url);
//            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
//            http.setRequestMethod("GET"); // 必须是get方式请求
//            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//            http.setDoOutput(true);
//            http.setDoInput(true);
//            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
//            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
//            http.connect();
//            InputStream is = http.getInputStream();
//            int size = is.available();
//            byte[] jsonBytes = new byte[size];
//            is.read(jsonBytes);
//            String result = new String(jsonBytes, "UTF-8");
//
//            JSONObject jsonObject = new JSONObject(result);
//            System.err.println(jsonObject);
//            accessToken = jsonObject.getString("access_token");
//            System.err.println(accessToken);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }



        RestTemplate restTemplate = new RestTemplate();

        try {
            String str = restTemplate.getForObject(url, String.class);
            System.err.println("str==" + str);
            accessToken = new JSONObject(str).getString("access_token");
            System.err.println(accessToken);
        } catch (JSONException e) {
            System.err.println("获取access_token失败");

        }
        return accessToken;

    }
}
